﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ABDLight.Components
{
    public partial class pr_Grid : UserControl
    {
        private Int32 ParentID = 0;

        public pr_Grid()
        {
            InitializeComponent();
        }

        public void LoadGrig(DataTable dt)
        {
            try
            {
                Grid.DataSource = dt.DefaultView;
                Grid.ColumnHeadersVisible = true;
               
                if (Grid.Columns["iqParentID"] != null) Grid.Columns["iqParentID"].Visible = false;
                if (Grid.Columns["iqParentID"] != null) Grid.Columns["iqParentID"].ReadOnly = true;
                if (Grid.Columns["ID_IQ"] != null) Grid.Columns["ID_IQ"].ReadOnly = true;



                /*
                    if (Grid.Columns["isCheck"] != null) Grid.Columns["isCheck"].DefaultHeaderCellType = System.Type.GetType("System.Bool");
                    if (Grid.Columns["isChanget"] != null) Grid.Columns["isChanget"].ReadOnly = true;
                    if (Grid.Columns["isBad"] != null) Grid.Columns["isBad"].ReadOnly = true;
                */



                for (int i = 0; i < Grid.ColumnCount; i++)
                {
                    Grid.Columns[i].HeaderText = ((DataView)Grid.DataSource).Table.Columns[i].Caption;
                }
                Grid.Refresh();
                Setcolumns();
            }
            catch(Exception e)
            {
                Grid.Invoke((MethodInvoker)delegate
                {
                    Grid.DataSource = dt.DefaultView;
                    Grid.ColumnHeadersVisible = true;

                    if (Grid.Columns["iqParentID"] != null) Grid.Columns["iqParentID"].Visible = false;
                    if (Grid.Columns["iqParentID"] != null) Grid.Columns["iqParentID"].ReadOnly = true;
                    if (Grid.Columns["ID_IQ"] != null) Grid.Columns["ID_IQ"].ReadOnly = true;
                    for (int i = 0; i < Grid.ColumnCount; i++)
                    {
                        Grid.Columns[i].HeaderText = ((DataView)Grid.DataSource).Table.Columns[i].Caption;
                    }
                    Grid.Refresh();
                    Setcolumns();
                });
            }
        }

        public Int32 SetParent(Int32 _parentid)
        {
            ParentID = _parentid;
            ((DataView)Grid.DataSource).RowFilter = "iqParentID = " + ParentID.ToString();
            return Grid.Rows.Count > 1 ? Int32.Parse(Grid.Rows[0].Cells["ID_IQ"].Value.ToString()) : 0;
        }

        private void btnFilter_Click(object sender, EventArgs e)
        {
            int stop = 0;
            if (cmbField.SelectedIndex!=-1)
            {
                if (((DataView)Grid.DataSource).Table.Columns[cmbField.SelectedValue.ToString()].DataType ==
                    System.Type.GetType("System.String"))
                {
                    ((DataView)Grid.DataSource).RowFilter = cmbField.SelectedValue.ToString() + string.Format(" like '%{0}%'", edFilter.Text.Trim().Replace("'", "''")) + (ParentID > 0 ? " and iqParentID=" + ParentID.ToString() : "");
                    stop += 1;
                }
                else if (((DataView)Grid.DataSource).Table.Columns[cmbField.SelectedValue.ToString()].DataType ==
                    System.Type.GetType("System.String"))
                {
                    ((DataView)Grid.DataSource).RowFilter = cmbField.SelectedValue.ToString() + string.Format(" like '%{0}%'", edFilter.Text.Trim().Replace("'", "''")) + (ParentID > 0 ? " and iqParentID=" + bool.Parse(ParentID.ToString()) : "");
                }
            }
            
        }


        private void Setcolumns()
        {
            if (Grid.DataSource == null) return;

            DataTable cols = new DataTable();
            cols.Columns.Add("Name");
            cols.Columns.Add("Caption");

            /*
            foreach (DataGridViewColumn column in this.dataGrid.Columns)
            {
                column.ValueType = typeof(DateTime);
            }
            DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn()
            dataGridView1.Columns.Add(col);
             */
            foreach (DataColumn col in ((DataView)Grid.DataSource).Table.Columns)
            {
                if (col.ColumnName != "iqParentID")
                {
                    DataRow dr = cols.NewRow();

                    dr["Name"] = col.ColumnName;
                    dr["Caption"] = col.Caption;
                    //col.DataType = System.Type.GetType("System.Boolean");
            
                    cols.Rows.Add(dr);
                }
            }

            cmbField.DataSource = cols.DefaultView;
            cmbField.ValueMember = "Name";
            cmbField.DisplayMember = "caption";


        }

        private void btnReplace_Click(object sender, EventArgs e)
        {
            frmReplace frm = new frmReplace(Grid,cmbField.SelectedValue.ToString());
            frm.Owner = this.ParentForm;
            frm.ShowDialog();
        }

        private void btnSortAZ_Click(object sender, EventArgs e)
        {
            ((DataView)Grid.DataSource).Sort=cmbField.Text + " ASC ";
        }

        private void btnSortZA_Click(object sender, EventArgs e)
        {
            ((DataView)Grid.DataSource).Sort = cmbField.Text + " DESC ";
        }

        private void Grid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
           
            cmbField.SelectedValue = Grid.Columns[e.ColumnIndex].Name;
        }

        private void pr_Grid_DoubleClick(object sender, EventArgs e)
        {

        }

        public void Grid_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            int SelRow  = Grid.Rows[e.RowIndex].Index; 
   
            if (e.RowIndex <= ((DataView)Grid.DataSource).Count)
            {
                if ((this.ParentForm.Name.ToLower() == "frmclean") && (this.Name.ToLower() == "grdmain"))
                {
                   ((frmClean)this.ParentForm).OneRowClean(e.RowIndex);
                }               
            }            
        }

        public void Grid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            
            if (e == null) {
                if (frmClean.cCfg.LastSelectedRow <= ((DataView)Grid.DataSource).Count)
                {
                   

                    if ((this.ParentForm.Name.ToLower() == "frmclean") && (this.Name.ToLower() == "grdmain"))
                    {
                        if (frmClean.cCfg.FuncType == "add")
                        {
                            return;
                        }

                        //frmClean.cCfg.FuncType = "select";
                        frmClean.cCfg.NumItem = 0;
                        ((frmClean)this.ParentForm).OneRowClean(frmClean.cCfg.LastSelectedRow);
                        //frmClean.cCfg.LastSelectedRow = frmClean.cCfg.LastSelectedRow;

                        if (frmClean.cCfg.FuncType == "update")
                        {                          
                            frmClean.cCfg.NumItem = 0;
                            ((frmClean)this.ParentForm).OneRowClean(frmClean.cCfg.LastSelectedRow);
                            frmClean.cCfg.FuncType = "select";
                            //frmClean.cCfg.LastSelectedRow = frmClean.cCfg.LastSelectedRow;
            

                        }

                    }
                    else if ((this.ParentForm.Name.ToLower() == "frmclean") && (this.Name.ToLower() == "grdmain"))
                    {
                      

                        frmClean.cCfg.FuncType = "update";

                        frmClean.cCfg.NumItem = frmClean.cCfg.LastSelectedRow;
                        ((frmClean)this.ParentForm).OneRowClean(frmClean.cCfg.LastSelectedRow);

                    }
                }
                return;
            }
            if (e.RowIndex <= ((DataView)Grid.DataSource).Count && e.RowIndex >= 0)
            {

                if ((this.ParentForm.Name.ToLower() == "frmclean") && (this.Name.ToLower() == "grdmain"))
                {
                
                    frmClean.cCfg.LastSelectedRow = Convert.ToInt32(this.Grid.Rows[e.RowIndex].Cells["ID_IQ"].Value.ToString()) - 1;
                    if (frmClean.cCfg.FuncType == "add")
                    {
                        return;
                    }

                    frmClean.cCfg.FuncType = "select";
                    frmClean.cCfg.NumItem = 0;
                    ((frmClean)this.ParentForm).OneRowClean(frmClean.cCfg.LastSelectedRow,true,false);
                }
                else if ((this.ParentForm.Name.ToLower() == "frmclean" || this.ParentForm.Name.ToLower() == "frmcleanaddress") && (this.Name.ToLower() == "grdvariant"))
                {
                    if (frmClean.cCfg.FuncType == "add")
                    {
                        return;
                    }
                    var result = MessageBox.Show("Выбрать этот вариант?", "Внимание",
                                                  MessageBoxButtons.YesNo,
                                                  MessageBoxIcon.Question);
                    if (result == DialogResult.No)
                    {
                        return;
                    }

                    
                    frmClean.cCfg.FuncType = "update";

                    frmClean.cCfg.NumItem = e.RowIndex;
                    ((frmCleanAddress)this.ParentForm).OneRowClean(frmClean.cCfg.LastSelectedRow, false);
                    
                }
            }

        }

        public void Grid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
 

        }

        private void Grid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
      
        }
        


        private void pr_Grid_BackColorChanged(object sender, EventArgs e)
        {

        }

        private void Grid_Paint(object sender, PaintEventArgs e)
        {

        }

        public void Grid_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if ((this.ParentForm.Name.ToLower() == "frmclean") && (this.Name.ToLower() == "grdmain"))
            {
                if (Grid["textStatus", e.RowIndex] != null && Grid["textStatus", e.RowIndex].Value != null)
                {
                    if (Grid["textStatus", e.RowIndex].Value.ToString().ToLower() == "хороший")
                    {
                        Grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightGreen;
                        return;
                    }
                    if (Grid["textStatus", e.RowIndex].Value.ToString().ToLower() == "плохой")
                    {
                        Grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightPink;
                        return;
                    }
                    if (Grid["textStatus", e.RowIndex].Value.ToString().ToLower() == "сомнительный")
                    {
                        Grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightGoldenrodYellow;
                        return;
                    }
                }
            }

        }

        private void Grid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            //try
            //{
            //    if (((DataView)Grid.DataSource) != null)
            //    {
            //        if (e.RowIndex == ((DataView)Grid.DataSource).Count)
            //        {
            //            //Console.WriteLine("{0}, - , {1}", ((DataView)Grid.DataSource).Count.ToString(), e.RowIndex.ToString()); 
            //            if ((this.ParentForm.Name.ToLower() == "frmclean") && (this.Name.ToLower() == "grdmain"))
            //            {
            //                ((frmClean)this.ParentForm).autoStartCleaner();
            //            }
            //        }
            //    }             
            //}
            //catch
            //{
            //    if (((DataTable)Grid.DataSource) != null)
            //    {
            //        if (e.RowIndex == ((DataTable)Grid.DataSource).Rows.Count)
            //        {
            //            //Console.WriteLine("{0}, - , {1}", ((DataView)Grid.DataSource).Count.ToString(), e.RowIndex.ToString()); 
            //            if ((this.ParentForm.Name.ToLower() == "frmclean") && (this.Name.ToLower() == "grdmain"))
            //            {
            //                ((frmClean)this.ParentForm).autoStartCleaner();
            //            }
            //        }
            //    }             
            //}
           
           
        }

        private void Grid_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
        {
           
            
        }

        private void Grid_ControlAdded(object sender, ControlEventArgs e)
        {
           
        }

    }

}